using FastCode.Architecture;
using FastCode.DTO;
using FastCode.Helper;
using FastCode.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FastCode.Controllers
{

    public class RouteConfigController : ApiControllerBase<RouteConfig>
    {
        public RouteConfigController(ISqlSugarClient _db) : base(_db) { }
        

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public override async Task<object> GetAllData()
        {
            var query = GetBaseQuery<RouteConfig>();
            var list = await query.ToListAsync();
            return Msg.Success(list);
        }

        /// <summary>
        /// 获取树形菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<object> GetTreeData()
        {
            var query = GetBaseQuery<RouteConfig>();
            var list = await query.OrderBy(x => x.Order).ToListAsync();
            
            // 构建树形结构
            var treeData = BuildMenuTree(list);
            
            return Msg.Success(treeData);
        }

        /// <summary>
        /// 获取树形列表数据（支持分页和搜索）
        /// </summary>
        /// <param name="queryBase"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<object> List([FromBody] QueryBase queryBase)
        {
            try
            {
                RefAsync<int> totalNumber = 0;

                var query = db.Queryable<RouteConfig>().Where(x => !x.IsDeleted);

                // 解析 SearchCondition 并构建查询条件
                if (queryBase.SearchConditions != null && queryBase.SearchConditions.Any())
                {
                    foreach (var searchConditions in queryBase.SearchConditions)
                    {
                        if (searchConditions.ConditionalModels == null || !searchConditions.ConditionalModels.Any())
                        {
                            return Msg.Error("SearchConditions 中的 ConditionalModels 不能为空");
                        }
                        
                        foreach (var condition in searchConditions.ConditionalModels)
                        {
                            if (!condition.FieldValue.IsHasValue())
                            {
                                continue;
                            }

                            if (condition.FieldName.EndsWith(ConstData.SplitStart))
                            {
                                condition.FieldName = condition.FieldName.Replace(ConstData.SplitStart, string.Empty);
                            }
                            else if (condition.FieldName.EndsWith(ConstData.SplitEnd))
                            {
                                condition.FieldName = condition.FieldName.Replace(ConstData.SplitEnd, string.Empty);
                            }
                            query = query.Where(new List<IConditionalModel>() { condition });
                        }
                    }
                }

            // 获取所有数据用于构建树形结构
            var allData = await query.OrderBy(x => x.Order).ToListAsync();
            
            // 构建树形结构
            var treeData = BuildMenuTree(allData);
            
            // 计算总数（包括子节点）
            var totalCount = CalculateTreeCount(treeData);
            
            // 分页处理（这里简化处理，实际项目中可能需要更复杂的分页逻辑）
            var pagedData = treeData;
            if (queryBase.pageSize > 0)
            {
                pagedData = treeData.Skip((queryBase.pageIndex - 1) * queryBase.pageSize).Take(queryBase.pageSize).ToList();
            }

            var columnNames = new List<ColumnConfig>();

            return Msg.Success(new { list = pagedData, columnNames = columnNames.OrderBy(x => x.Order), totalNumber = totalCount });
            }
            catch (Exception ex)
            {
                return Msg.Error($"获取数据失败: {ex.Message}", ex.StackTrace);
            }
        }

        /// <summary>
        /// 构建菜单树形结构
        /// </summary>
        /// <param name="menuList"></param>
        /// <returns></returns>
        private List<RouteConfig> BuildMenuTree(List<RouteConfig> menuList)
        {
            var tree = new List<RouteConfig>();
            var menuDict = menuList.ToDictionary(x => x.Id);

            foreach (var menu in menuList)
            {
                if (menu.ParentId == 0)
                {
                    // 顶级菜单
                    tree.Add(menu);
                }
                else
                {
                    // 子菜单
                    if (menuDict.ContainsKey(menu.ParentId))
                    {
                        var parent = menuDict[menu.ParentId];
                        if (parent.Children == null)
                        {
                            parent.Children = new List<RouteConfig>();
                        }
                        parent.Children.Add(menu);
                    }
                }
            }

            return tree;
        }

        /// <summary>
        /// 计算树形结构的总节点数
        /// </summary>
        /// <param name="treeData"></param>
        /// <returns></returns>
        private int CalculateTreeCount(List<RouteConfig> treeData)
        {
            int count = 0;
            foreach (var item in treeData)
            {
                count++;
                if (item.Children != null && item.Children.Any())
                {
                    count += CalculateTreeCount(item.Children);
                }
            }
            return count;
        }

        [HttpPost]
        public async Task<object> DelRoute([FromBody] RouteConfig entity)
        {

            var nowTime = DateTime.Now;
            if (entity.Id == 0)
            {
                
                return Msg.Success(message: "id不能为空");
            }


            return Msg.Success(message: "删除成功");
        }

    }
}
